package com.cn.parks.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录检查过滤器
 */
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();
        
        String requestURI = httpRequest.getRequestURI();
        
        // 不需要过滤的URL
        if (isExcludedUrl(requestURI)) {
            chain.doFilter(request, response);
            return;
        }

        // 检查是否已登录
        if (session != null && session.getAttribute("user") != null) {
            chain.doFilter(request, response);
        } else {
            // 如果是AJAX请求，返回JSON响应
            if ("XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With"))) {
                httpResponse.setContentType("application/json;charset=UTF-8");
                httpResponse.getWriter().write("{\"success\":false,\"message\":\"未登录或会话已过期\"}");
            } else {
                // 普通请求重定向到登录页
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.html");
            }
        }
    }

    private boolean isExcludedUrl(String url) {
        return url.endsWith("login.html") ||
               url.endsWith("login.js") ||
               url.endsWith("login.css") ||
               url.endsWith("/login") ||
               url.contains("/css/") ||
               url.contains("/js/") ||
               url.contains("/fonts/") ||
               url.contains("/images/");
    }

    @Override
    public void destroy() {
    }
} 